package com.kczd.activity;

import android.content.Intent;
import android.graphics.Color;

import android.os.Handler;
import android.os.Message;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.kczd.client.R;
import com.kczd.entity.Driver;
import com.kczd.util.Common;
import com.kczd.util.NetRET;
import com.kczd.util.ObjectSaveUtil;
import com.kczd.util.SysApplication;


import org.json.JSONException;
import org.json.JSONObject;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.kczd.util.Common.CONNECT_TIMEOUT;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_regist;
    private TextView tv_forgetPswd;
    private ImageView iv_login;

    private EditText et_phone;
    private EditText et_passwd;

    private ImageView iv_showPassword;
    private Boolean showPassword = true;
    SweetAlertDialog pDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        // 多activity管理
        SysApplication.getInstance().addActivity(this);
    }

    public void initView(){
        tv_regist = (TextView) findViewById(R.id.tv_regist);
        tv_forgetPswd = (TextView) findViewById(R.id.tv_forgetPswd);
        iv_login = (ImageView) findViewById(R.id.iv_login);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_passwd = (EditText) findViewById(R.id.et_passwd);
        iv_showPassword = (ImageView) findViewById(R.id.iv_showPassword);
        iv_showPassword.setImageDrawable(getResources().getDrawable(R.mipmap.eye_c));

        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading");
        pDialog.setCancelable(false);

        tv_regist.setOnClickListener(this);
        tv_forgetPswd.setOnClickListener(this);
        iv_login.setOnClickListener(this);
        iv_showPassword.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            SysApplication.getInstance().exit();
            System.exit(0);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_login:
                if(!subpre()){
                    new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("必填验证")
                            .setContentText("你是不是忘了填什么")
                            .show();
                    return;
                }else{
                    pDialog.show();
                    new Thread(){
                        @Override
                        public void run()
                        {
                            loginHandle();
                        }
                    }.start();
                }
                break;

            case R.id.iv_showPassword:
                if(showPassword){//显示密码
                    showPassword = !showPassword;
                    iv_showPassword.setImageDrawable(getResources().getDrawable(R.mipmap.eye_o));
                    et_passwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    et_passwd.setSelection(et_passwd.getText().toString().length());
                }else{//隐藏密码
                    showPassword = !showPassword;
                    iv_showPassword.setImageDrawable(getResources().getDrawable(R.mipmap.eye_c));
                    et_passwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    et_passwd.setSelection(et_passwd.getText().toString().length());
                }
                break;
            case R.id.tv_regist:
                startActivity(new Intent(this, RegisterActivity.class));//打开注册页面
                this.finish();
                break;

            case R.id.tv_forgetPswd:
                startActivity(new Intent(this, FindBackPasswordActivity.class));//打开设置密码页面
                break;

            default:
                break;
        }
    }

    public boolean subpre(){
        String phone= et_phone.getText().toString();
        String paswd= et_passwd.getText().toString();

        if(phone.isEmpty() || paswd.isEmpty()){
            return false;
        }
        return true;
    }
    
    String url = Common.net_addr + "itf/tx_login_app.php";
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);

            JSONObject jsonResult;
            try {
                pDialog.dismiss();
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
                    Common.user=new Driver();
                    Common.user.Json2Object1(jsonResult);
                    // 永久化存储对象
                    ObjectSaveUtil.saveObject(getBaseContext(), Common.user);
                    // 进入主界面
                    LoginActivity.this.finish();
                    Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                }else{
                    new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText("登陆失败："+jsonResult.getString("err"))
                            .show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    public void loginHandle() {
         //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
       RequestBody requestBody=new FormBody.Builder()
               .add("phone", et_phone.getText().toString())
               .add("password", et_passwd.getText().toString())
               .add("utype", Common.utype)
               .add("platform", Common.platform)
               .add("tran_type", Common.tran_type)
               .add("channelId", Common.clientid)
               .build();
        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();
                Message msg = new Message();
                Bundle data = new Bundle();
                data.putString("ret_json", strResult);
                msg.setData(data);
                handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
